package cxbks.java.service.impl;

import com.mongodb.client.result.DeleteResult;
import cxbks.java.dao.entity.User;
import cxbks.java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;

/**
 * @Author:
 * @CreateTime: 2021-09-14 11:02
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Override
	public User save(User user) {
		//使用 save和insert都可以进行插入
		//区别：当存在"_id"时
		//insert 插入已经存在的id时 会异常
		//save 则会进行更新
		//简单来说 save 就是不存在插入 存在更新
		mongoTemplate.insert(user);
		mongoTemplate.save(user);
		return user;
	}

	@Override
	public Collection<User> saveAll(List<User> userList) {
		return mongoTemplate.insertAll(userList);
	}

	@Override
	public List<User> findAll() {
		return mongoTemplate.findAll(User.class);
	}

	@Override
	public User findById(String id) {
		Query query = new Query(Criteria.where("id").is(id));
		return mongoTemplate.findOne(query, User.class);
	}

	@Override
	public long countUser(String id) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id));
		return mongoTemplate.count(query, User.class);
	}

	@Override
	public List<User> findPageUser(int begin, int end) {
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "updateDate"));
		// 从那条记录开始
		query.skip(begin);
		// 取多少条记录
		query.limit(end - begin);
		return mongoTemplate.find(query, User.class);
	}

	@Override
	public List<User> findByNickNameLike(String nickname) {
		Query query = new Query();
		query.addCriteria(Criteria.where("nickName").regex(".*?\\" + nickname + ".*"));
		return mongoTemplate.find(query, User.class);
	}

	@Override
	public DeleteResult delete(String id) {
		Query query = new Query(Criteria.where("id").is(id));
		return mongoTemplate.remove(query, User.class);
	}

	@Override
	public User update(User user) {
		return mongoTemplate.save(user);
	}

	@Override
	public DeleteResult deleteAll() {
		Query query = new Query();
		return mongoTemplate.remove(query, User.class);
	}
}
